<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2019 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------

namespace app\api\controller;

use spec\Prophecy\Doubler\ClassPatch\TraversablePatchSpec;
use think\Db;
use think\Request;
use think\facade\Config;
use app\common\service\CommonService;
use think\testing\InteractsWithPages;

/**
 * 空气质量预报 - 特征分析
 */
class AirQualityFeatureAnalysis extends BaseController
{

    //2.2-1首要污染物分析---------------------------------------------------------------------------------

    /**
     * 空气质量预报值(全市、站点公用接口)
     */
    public function airQualityPrediction()
    {
        $param = $this->request->param();
        if (empty($param['region_id']) || empty($param['start_date']) || empty($param['end_date'])) {
            $this->error('参数错误');
        }
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        $data['date'] = $lastYearWeek;
        //通过日期判断是预测值还是实际值
        if (strtotime($param['end_date']) <= strtotime(date('Y-m-d', time()))) {
            //实际值(上周或者过去时间段)
            $sql_history = "select pm10,pm25,so2,no2,co,o3,o3_8hour,o3_iaqi,o3_8hour_iaqi,publish_time as pt_time from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
            $list        = Db::query($sql_history, array($param['region_id'], $param['station_id'], $param['start_date'].' 00:00:00', $param['end_date'].' 23:00:00'));
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d', time())) + 1;
            if ($days > 1) {
                //实际+预报（本周或者今天日期在所选日期范围内）
                //实际
                $sql_week = "select pm10,pm25,so2,no2,co,o3,o3_8hour,o3_iaqi,o3_8hour_iaqi,publish_time as pt_time from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
                $weekList = Db::query($sql_week, array($param['region_id'], $param['station_id'], $param['start_date'].' 00:00:00', date("Y-m-d 23:00:00", strtotime("-1 day"))));
                //预报
                $sql_forecast = "select pm10,pm25,so2,no2,co,o3,o3_8hour,o3_iaqi,o3_8h_iaqi as o3_8hour_iaqi, predict_time as pt_time from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                $forecastList = Db::query($sql_forecast, array($param['region_id'], $param['station_id'], date("Y-m-d 00:00:00", time()), $param['end_date'].' 23:00:00', date("Y-m-d 00:00:00", time())));
                if (count($weekList) > 0 && count($forecastList) > 0) {
                    $list = array_merge_recursive($weekList, $forecastList);
                } else {
                    if (count($weekList) > 0) {
                        $list = $weekList;
                    }
                    if (count($forecastList) > 0) {
                        $list = $forecastList;
                    }
                }
            } else {
                //预报（未来日期范围，包括今天）
                $sql  = "select pm10,pm25,so2,no2,co,o3,o3_8hour,o3_iaqi,o3_8h_iaqi as o3_8hour_iaqi,predict_time as pt_time from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                $list = Db::query($sql, array($param['region_id'], $param['station_id'], $param['start_date'].' 00:00:00', $param['end_date'].' 23:00:00', date("Y-m-d 00:00:00", time())));
            }
        }
        if (count($list) <= 0) {
            foreach ($lastYearWeek as $k => $v) {
                $data['data'][0][] = '';
                $data['data'][1][] = '';
                $data['data'][2][] = '';
                $data['data'][3][] = '';
                $data['data'][4][] = '';
                $data['data'][5][] = '';
            }
        } else {
            $newList = [];
            $newDate = [];
            for ($i = 0; $i < count($list); $i++) {
                foreach ($list[$i] as $k => $v) {
                    if ($k != 'pt_time') {
                        if ($k == 'co' || $k == 'CO') {
                            $list[$i][$k] = round($v, 1);
                        } elseif(strtolower($k) == 'o3'){
                            if ($list[$i]['o3_iaqi'] >= $list[$i]['o3_8hour_iaqi']) {
                                $list[$i]['o3'] = round($list[$i]['o3']);
//                                $param['pollutant'] = 'o3';
                            } else {
                                $list[$i]['o3'] = round($list[$i]['o3_8hour']);
//                                $param['pollutant'] = 'o3_8hour';
                            }
                        } else {
                            $list[$i][$k] = round($v);
                        }
                    }
                }
                $newList[date("m/d", strtotime($list[$i]['pt_time']))][] = $list[$i];
                array_push($newDate, date('m/d', strtotime($list[$i]['pt_time'])));
            }
            $newDate = array_values(array_unique($newDate));//去重，重新排列索引

            foreach ($lastYearWeek as $k => $v) {
                if (in_array($v, $newDate)) {
                    $data['data'][0][] = isset($newList[$v][0]['pm10']) && $newList[$v][0]['pm10'] >= 0 ? $newList[$v][0]['pm10'] : '';
                    $data['data'][1][] = isset($newList[$v][0]['pm25']) && $newList[$v][0]['pm25'] >= 0 ? $newList[$v][0]['pm25'] : '';
                    $data['data'][2][] = isset($newList[$v][0]['so2']) && $newList[$v][0]['so2'] >= 0 ? $newList[$v][0]['so2'] : '';
                    $data['data'][3][] = isset($newList[$v][0]['no2']) && $newList[$v][0]['no2'] >= 0 ? $newList[$v][0]['no2'] : '';
                    $data['data'][4][] = isset($newList[$v][0]['o3']) && $newList[$v][0]['o3'] >= 0 ? $newList[$v][0]['o3'] : '';
                    $data['data'][5][] = isset($newList[$v][0]['co']) && $newList[$v][0]['co'] >= 0 ? $newList[$v][0]['co'] : '';
                } else {
                    if ($v == date('m/d', time())) {
                        $sql       = "select pm10,pm25,so2,no2,co,o3,predict_time as pt_time from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time = ? and predict_time = publish_time";
                        $todayList = Db::query($sql, array($param['region_id'], $param['station_id'], date('Y-m-d', time())));
                        if (count($todayList) > 0) {
                            $data['data'][0][] = isset($todayList[0]['pm10']) && $todayList[0]['pm10'] >= 0 ? $todayList[0]['pm10'] : '';
                            $data['data'][1][] = isset($todayList[0]['pm25']) && $todayList[0]['pm25'] >= 0 ? $todayList[0]['pm25'] : '';
                            $data['data'][2][] = isset($todayList[0]['so2']) && $todayList[0]['so2'] >= 0 ? $todayList[0]['so2'] : '';
                            $data['data'][3][] = isset($todayList[0]['no2']) && $todayList[0]['no2'] >= 0 ? $todayList[0]['no2'] : '';
                            $data['data'][4][] = isset($todayList[0]['o3']) && $todayList[0]['o3'] >= 0 ? $todayList[0]['o3'] : '';
                            $data['data'][5][] = isset($todayList[0]['co']) && $todayList[0]['co'] >= 0 ? $todayList[0]['co'] : '';
                        } else {
                            $data['data'][0][] = '';
                            $data['data'][1][] = '';
                            $data['data'][2][] = '';
                            $data['data'][3][] = '';
                            $data['data'][4][] = '';
                            $data['data'][5][] = '';
                        }
                    } else {
                        $data['data'][0][] = '';
                        $data['data'][1][] = '';
                        $data['data'][2][] = '';
                        $data['data'][3][] = '';
                        $data['data'][4][] = '';
                        $data['data'][5][] = '';
                    }

                }
            }
        }
        $this->success('成功', $data);
    }


    /**
     * 首要污染物（全市、站点公用接口）
     */
    public function firstContaminants()
    {
        $param = $this->request->param();
        if (empty($param['region_id']) || empty($param['start_date']) || empty($param['end_date'])) {
            $this->error('参数错误');
        }
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        $data['date'] = $lastYearWeek;
        //通过日期判断是预测值还是实际值
        if (strtotime($param['end_date']) <= strtotime(date('Y-m-d', time()))) {
            //实际值(上周或者过去时间段)
            $sql_history = "select name,value,publish_time as pt_time from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
            $list        = Db::query($sql_history, array($param['region_id'], $param['station_id'], $param['start_date'].' 00:00:00', $param['end_date'].' 23:00:00'));
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d', time()))+1;
            if ($days > 1) {
                //实际+预报（本周或者今天日期在所选日期范围内）
                //实际
                $sql_week = "select name,value,publish_time as pt_time from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
                $weekList = Db::query($sql_week, array($param['region_id'], $param['station_id'], $param['start_date'].' 00:00:00', date("Y-m-d 23:00:00", strtotime("-1 day"))));
                //预报
                $sql_forecast = "select name,value,predict_time as pt_time from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                $forecastList = Db::query($sql_forecast, array($param['region_id'], $param['station_id'], date("Y-m-d 00:00:00", time()), $param['end_date'].' 23:00:00', date("Y-m-d", time())));
                if (count($weekList) > 0 && count($forecastList) > 0) {
                    $list = array_merge($weekList, $forecastList);
                } else {
                    if (count($weekList) > 0) {
                        $list = $weekList;
                    } else if (count($forecastList) > 0) {
                        $list = $forecastList;
                    } else {
                        $list = [];
                    }
                }
            } else {
                //预报（未来日期范围，包括今天）
                $sql  = "select name,value,predict_time as pt_time from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                $list = Db::query($sql, array($param['region_id'], $param['station_id'], $param['start_date'].' 00:00:00', $param['end_date'].' 23:00:00', date("Y-m-d", time())));
            }
        }
        if (count($list) <= 0) {
            foreach ($lastYearWeek as $k => $v) {
                $data['data'][0][] = ['name' => '', 'value' => ''];
            }
        } else {
            $newList = [];
            $newDate = [];
            for ($i = 0; $i < count($list); $i++) {
                if ($list[$i]['name'] == 'co' || $list[$i]['name'] == 'CO') {
                    $list[$i]['value'] = round($list[$i]['value'], 1);
                } else {
                    $list[$i]['value'] = round($list[$i]['value']);
                }
                $newList[date("m/d", strtotime($list[$i]['pt_time']))][] = $list[$i];
                array_push($newDate, date('m/d', strtotime($list[$i]['pt_time'])));
            }
            $newDate = array_values(array_unique($newDate));//去重，重新排列索引
            foreach ($newList as $k1 => $v1) {
                //处理O3和O3_8H
                for ($i = 0; $i < count($v1); $i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList[$k1], $i, 1);//删除数组元素，索引重组
                        }
                    }
                }
            }
            $temp = [];
            foreach ($newList as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            foreach ($lastYearWeek as $k => $v) {
                for ($j = 0; $j < max($temp); $j++) {
                    if (isset($newList[$v][$j])) {
                        if (in_array($v, $newDate)) {
                            if (strtoupper($newList[$v][$j]['name']) == 'O3_8H') {
                                $newList[$v][$j]['name'] = 'O3';
                            }
                            $data['data'][$j][] = ['name' => strtoupper($newList[$v][$j]['name']), 'value' => $newList[$v][$j]['value']];
                        } else {
                            $data['data'][$j][] = ['name' => '', 'value' => ''];
                        }
                    } else {
                        $data['data'][$j][] = ['name' => '', 'value' => ''];
                    }
                }

            }
        }
        $this->success('成功', $data);

    }

    /**
     * 减排前贡献度（全市、站点公用接口,查询MongoDB）
     */
    public function reductionContributionBefor()
    {
        //链接MongoDB数据库（远程）
        $PDOManager = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $opt        = [
            'projection' => [
                '_id' => 0
            ],
        ];
        $param      = $this->request->param();

        if (empty($param['region_id']) || empty($param['industry_id']) || empty($param['start_date']) || empty($param['end_date'])) {
            $this->error('参数错误');
        }
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        $data['date'] = $lastYearWeek;
        //返回年月日
        $yearWeek     = self::getDateFromRangeYear($param['start_date'], $param['end_date']);
        $data['time'] = $yearWeek;

        // 1工业、2非工业
        if ($param['industry_id'] == 1) {
            //条件参数
            $map          = [
                "region_id"  => (int)$param['region_id'],
                "station_id" => (int)$param['station_id'],//全市站点，暂时为1  正式数据station_id=0
                // "industry_id" => ['$in' => Config::get('industry_limit_arr_mongodb')],
                //  "company_id" => ['$lte' => $companyId->getCompanyLimitId()],
            ];
            $pollutantTab = 'huanxin.air_quality_pollutant_company_forecast_day';
            // $map['industry_id'] = ['$in' => Config::get('industry_limit_arr_mongodb')];
        } else {
            $map          = [
                // "region_id"  => (int)$param['region_id'],
                "station_id" => (int)$param['station_id'],//全市站点，暂时为1  正式数据station_id=0
                // "industry_id" => ['$in' => Config::get('no_industry_limit_arr_mongodb')],
            ];
            $pollutantTab = 'huanxin.air_quality_pollutant_non_industry_area_forecast_day';
        }
        //通过日期判断是预测值还是实际值
        if (strtotime($param['end_date']) < strtotime(date('Y-m-d'))) {
            //实际值(上周或者过去时间段)
            $map['predict_time'] = [
                '$gte' => date('Y-m-d 00:00:00', strtotime($param['start_date'])),
                '$lte' => date('Y-m-d 23:00:00', strtotime($param['end_date']))
            ];
            $map['$where']       = 'this.publish_time == this.predict_time';
            //预报值
            $query  = new \MongoDB\Driver\Query($map, $opt);//查询
            $cursor = $PDOManager->executeQuery($pollutantTab, $query)->toArray();
            $list   = json_decode(json_encode($cursor), true);
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d')) + 1;
            if ($days > 1) {
                //实际+预报(本周或者今天日期在所选日期范围内)
                //实际
                $map['$where']       = 'this.publish_time == this.predict_time';
                $map['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00', strtotime($param['start_date'])),
                    '$lte' => date('Y-m-d 23:00:00', strtotime('-1 day'))
                ];

                //实际值
                $query  = new \MongoDB\Driver\Query($map, $opt);//查询
                $cursor = $PDOManager->executeQuery($pollutantTab, $query)->toArray();
                $list1  = json_decode(json_encode($cursor), true);
                if (empty($list1)) {
                    $list1 = [];
                }
                //预报（未来日期范围，包括今天）
                unset($map['$where']);
                $map['publish_time'] = date('Y-m-d ' . (date('H:i') < '14:20' ? '00' : '14') . ':00:00');
                $map['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00'),
                    '$lte' => date("Y-m-d 23:00:00", strtotime($param['end_date']))
                ];
                //预报值
                $query  = new \MongoDB\Driver\Query($map, $opt);//查询
                $cursor = $PDOManager->executeQuery($pollutantTab, $query)->toArray();
                $list2  = json_decode(json_encode($cursor), true);
                if (empty($list2)) {
                    $list2 = [];
                }
                $list = array_merge_recursive($list1, $list2);
            } else {
                $map['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00'),
                    '$lte' => date('Y-m-d 00:00:00', strtotime($param['end_date']))
                ];
                $map['publish_time'] = date('Y-m-d ' . (date('H:i') < '14:20' ? '00' : '14') . ':00:00');
                //预报值
                $query  = new \MongoDB\Driver\Query($map, $opt);//查询
                $cursor = $PDOManager->executeQuery($pollutantTab, $query)->toArray();
                $list   = json_decode(json_encode($cursor), true);
            }

        }
        if (count($list) <= 0) {
            foreach ($lastYearWeek as $k => $v) {
                $data['data'][0][] = '';
                $data['data'][1][] = '';
                $data['data'][2][] = '';
            }
        } else {
            $newList = [];
            $newDate = [];
            for ($i = 0; $i < count($list); $i++) {
                $newList[date("m/d", strtotime($list[$i]['predict_time']))][] = $list[$i];
                array_push($newDate, date('m/d', strtotime($list[$i]['predict_time'])));
            }
            $newDate            = array_values(array_unique($newDate));//去重，重新排列索引
            $concentration_pm25 = '';
            $concentration_so2  = '';
            $concentration_no2  = '';
            $service            = new CommonService();
            foreach ($lastYearWeek as $k2 => $v2) {
                $pm25 = 0;
                $so2  = 0;
                $no2  = 0;
                if (in_array($v2, $newDate)) {
                    foreach ($newList[$v2] as $k => $v) {
                        if (strtoupper($v['contribution_name']) == 'PM2.5') {
                            $pm25               += $v['contribution_degree'];
                            $concentration_pm25 = $v['concentration'];
                        } else if (strtoupper($v['contribution_name']) == 'SO2') {
                            $so2               += $v['contribution_degree'];
                            $concentration_so2 = $v['concentration'];
                        } else {
                            $no2               += $v['contribution_degree'];
                            $concentration_no2 = $v['concentration'];
                        }
                    }
                    if (empty($concentration_pm25) && empty($pm25)) {
                        $data['data'][0][$k2] = 0;
                    } else {
                        $data['data'][0][$k2] = $service->contributionRound($pm25 / $concentration_pm25);//保留小数点有效三位
                    }
                    if (empty($concentration_so2) && empty($so2)) {
                        $data['data'][1][$k2] = 0;
                    } else {
                        $data['data'][1][$k2] = $service->contributionRound($so2 / $concentration_so2);
                    }
                    if (empty($concentration_no2) && empty($no2)) {
                        $data['data'][2][$k2] = 0;
                    } else {
                        $data['data'][2][$k2] = $service->contributionRound($no2 / $concentration_no2);
                    }
                } else {
                    $data['data'][0][$k2] = '';
                    $data['data'][1][$k2] = '';
                    $data['data'][2][$k2] = '';
                }
            }
        }
        $this->success('成功', $data);
    }


    /**
     * 贡献度明细（全市、站点公用接口）
     * @throws \MongoDB\Driver\Exception\Exception
     * @author zhugeng 2019-04-12
     * @edit dutongtong 2019-07-26 根据甲方需求修改
     */
    public function contributionInfo()
    {
        //链接MongoDB数据库（远程）
        $PDOManager = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $param      = $this->request->param();
        $validate   = V([
            'predict_time' => 'require',
            'region_id'    => 'require'
        ]);
        if (isset($validate['msg'])) {
            $this->error($validate['msg']);
        }
        $commonService              = new CommonService();
        $industryType               = $param['industry_id'];//1 - 工业, 2 - 非工业
        $param['contribution_name'] = str_replace('_', '', strtoupper($param['contribution_name']));

        if ($industryType == 1) {
            $pollutantTab = 'huanxin.air_quality_pollutant_company_forecast_day';
            //条件参数
            $map = [
                "region_id"         => (int)$param['region_id'],
                "station_id"        => (int)$param['station_id'],
                // "industry_id"       => $param['industry_id'],
                "contribution_name" => $param['contribution_name'],
                "predict_time"      => $param['predict_time'] . ' 00:00:00',
                // "company_id"        => ['$lte' => $commonService->getCompanyLimitId()],
            ];
        } else {
            $pollutantTab = 'huanxin.air_quality_pollutant_non_industry_area_forecast_day';
            //条件参数
            $map = [
                // "region_id"         => (int)$param['region_id'],
                "station_id"        => (int)$param['station_id'],
                // "industry_id"       => $param['industry_id'],
                "contribution_name" => $param['contribution_name'],
                "predict_time"      => $param['predict_time'] . ' 00:00:00',
            ];
        }

        $options = [
            "_id"  => 0,
            'sort' => ['contribution_value' => -1, 'company_id' => 1],
        ];
        if (strtotime($param['predict_time']) < strtotime(date('Y-m-d'))) {
            $map['$where'] = 'this.publish_time == this.predict_time';
        } else {
            //预报
            $map['publish_time'] = date('Y-m-d ' . (date('H:i') < '14:20' ? '00' : '14') . ':00:00');
        }
        //预报值
        $query  = new \MongoDB\Driver\Query($map, $options);//查询
        $cursor = $PDOManager->executeQuery($pollutantTab, $query)->toArray();
        $list   = json_decode(json_encode($cursor), true);
        $data   = [];

        $data['date'] = [];
        $data['data'] = [[]];
        $data['info'] = [];
        //工业类型
        if ($industryType == 1) {
            $companyList = Db::query('select id,short_name from basic_company where id <= 60');
            if (!empty($list)) {
                foreach ($list as $k => $v) {
                    foreach ($companyList as $k1 => $v1) {
                        if ($v['company_id'] == $v1['id']) {
                            $data['date'][] = $v1['short_name'];
                        }
                    }
                    $data['data'][0][] = $commonService->contributionRound($v['contribution_value']);
                }
            }
        } else {//非工业类型
            $nonIndustryList = Db::query('select id,name from basic_industry where id in ' . Config::get('no_industry_limit_arr'));
            $non             = [];
            if (!empty($list)) {
                foreach ($list as $lv) {
                    $non[$lv['industry_id']][$lv['non_industry_region_id']] = $non[$lv['industry_id']][$lv['non_industry_region_id']] ?? 0;
                    $non[$lv['industry_id']][$lv['non_industry_region_id']] += $lv['contribution_value'];
                }
            }
            $industry_area = Db::query('select id,name from basic_non_industry_area');
            foreach ($nonIndustryList as $k => $v) {
                $data['date'][] = $v['name'];
                if (!empty($list)) {
                    //行业列表
                    $info  = '';
                    $index = 1;
                    foreach ($industry_area as $v2) {
                        $exp = '  ';
                        if ($index % 4 == 0) {
                            $exp = '<br/>';
                        }
                        $contribution = $commonService->contributionRound($non[$v['id']][$v2['id']]);
                        $info         .= "{$v2['name']} : {$contribution}% {$exp}";
                        $index++;
                    }
                    $curIndustryVal    = $commonService->contributionRound(array_sum($non[$v['id']]));
                    $data['info'][$k]  = "{$v['name']} : {$curIndustryVal}%<br/><br/>{$info}";
                    $data['data'][0][] = $commonService->contributionRound(array_sum($non[$v['id']]));
                }
            }
        }

        $this->success('成功', $data);
    }


    //2.2-1相关性分析-----------------------------------------------------------------------

    /**
     * 相关指数（污染物）
     * zhugeng 2019-04-10
     */
    public function relevantExponent()
    {
        $param = $this->request->param();
        if (empty($param['start_date']) || empty($param['end_date']) || empty($param['region_id'])) {
            $this->error('参数错误');
        }
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        $data['date'] = $lastYearWeek;
        if (empty($param['contaminant_name1']) || empty($param['contaminant_name2'])) {
            $data['data'] = [];
            $this->success('暂无数据', $data);
        }
        $param['contaminant_name1'] = strtoupper($param['contaminant_name1']);
        $param['contaminant_name2'] = strtoupper($param['contaminant_name2']);
        $param['contaminant_name1'] = 'PM2.5' ? str_replace('.', '', $param['contaminant_name1']) : $param['contaminant_name1'];
        $param['contaminant_name2'] = 'PM2.5' ? str_replace('.', '', $param['contaminant_name2']) : $param['contaminant_name2'];

        //判断预报值还是实际值
        if (strtotime($param['end_date']) < strtotime(date('Y-m-d', time()))) {
            //实际值(上周或者过去时间段)
            if ($param['contaminant_name1'] == 'O3') {
                $sql_history1 = 'select O3,publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                $list_o3      = Db::query($sql_history1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00'));
                $sql_history1 = 'select o3_8hour,publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                $list_o38h    = Db::query($sql_history1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00'));
                //判断O3和O3_8h是否同时有数据，同时有数据选择O3_8h,否则哪个有数据取哪个
                if (!empty($list_o3) && !empty($list_o38h)) {
                    $list1 = $list_o38h;
                } else if (!empty($list_o3) && empty($list_o38h)) {
                    $list1 = $list_o3;
                } else if (empty($list_o3) && !empty($list_o38h)) {
                    $list1 = $list_o38h;
                }
                $sql_history2 = 'select ' . $param['contaminant_name2'] . ',publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                $list2        = Db::query($sql_history2, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00'));
            } else if ($param['contaminant_name2'] == 'O3') {
                $sql_history1 = 'select ' . $param['contaminant_name1'] . ',publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                $list1        = Db::query($sql_history1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00'));
                $sql_history2 = 'select ' . $param['contaminant_name2'] . ',publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                $list_o3      = Db::query($sql_history2, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00'));
                $sql_history2 = 'select o3_8hour,publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                $list_o38h    = Db::query($sql_history2, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00'));
                //判断O3和O3_8h是否同时有数据，同时有数据选择O3_8h,否则哪个有数据取哪个
                if (!empty($list_o3) && !empty($list_o38h)) {
                    $list2 = $list_o38h;
                } else if (!empty($list_o3) && empty($list_o38h)) {
                    $list2 = $list_o3;
                } else if (empty($list_o3) && !empty($list_o38h)) {
                    $list2 = $list_o38h;
                }
            } else {
                $sql_history1 = 'select ' . $param['contaminant_name1'] . ',publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                $list1        = Db::query($sql_history1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00'));
                $sql_history2 = 'select ' . $param['contaminant_name2'] . ',publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                $list2        = Db::query($sql_history2, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00'));
            }
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d', time())) + 1;
            if ($days > 1) {
                //实际+预报（本周或者今天日期在所选日期范围内）
                //实际
                $weekList1 = [];
                $weekList2 = [];
                if ($param['contaminant_name1'] == 'O3') {
                    $sql_week1     = 'select O3,publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                    $weekList_o3   = Db::query($sql_week1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', date("Y-m-d", strtotime("-1 day")) . ' 23:00:00'));
                    $sql_week1     = 'select o3_8hour,publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                    $weekList_o38h = Db::query($sql_week1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', date("Y-m-d", strtotime("-1 day")) . ' 23:00:00'));
                    //判断O3和O3_8h是否同时有数据，同时有数据选择O3_8h,否则哪个有数据取哪个

                    if (!empty($weekList_o3) && !empty($weekList_o38h)) {
                        $weekList1 = $weekList_o38h;
                    } else if (!empty($weekList_o3) && empty($weekList_o38h)) {
                        $weekList1 = $weekList_o3;
                    } else if (empty($weekList_o3) && !empty($weekList_o38h)) {
                        $weekList1 = $weekList_o38h;
                    }
                    $sql_week2 = 'select ' . $param['contaminant_name2'] . ',publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                    $weekList2 = Db::query($sql_week2, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', date("Y-m-d", strtotime("-1 day")) . ' 23:00:00'));
                    //预报
                    $sql_forecast1     = 'select O3,station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $forecastList_o3   = Db::query($sql_forecast1, array($param['region_id'], $param['station_id'], date("Y-m-d", time()) . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                    $sql_forecast1     = 'select o3_8hour,station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $forecastList_o38h = Db::query($sql_forecast1, array($param['region_id'], $param['station_id'], date("Y-m-d", time()) . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                    //判断O3和O3_8h是否同时有数据，同时有数据选择O3_8h,否则哪个有数据取哪个
                    if (!empty($forecastList_o3) && !empty($forecastList_o38h)) {
                        $forecastList1 = $forecastList_o38h;
                    } else if (!empty($forecastList_o3) && empty($forecastList_o38h)) {
                        $forecastList1 = $forecastList_o3;
                    } else if (empty($forecastList_o3) && !empty($forecastList_o38h)) {
                        $forecastList1 = $forecastList_o38h;
                    }

                    $sql_forecast2 = 'select ' . $param['contaminant_name2'] . ',station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $forecastList2 = Db::query($sql_forecast2, array($param['region_id'], $param['station_id'], date("Y-m-d", time()) . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                } else if ($param['contaminant_name2'] == 'O3') {
                    $sql_week1 = 'select ' . $param['contaminant_name1'] . ',publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                    $weekList1 = Db::query($sql_week1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', date("Y-m-d", strtotime("-1 day")) . ' 23:00:00'));

                    $sql_forecast2     = 'select O3,station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $forecastList_o3   = Db::query($sql_forecast2, array($param['region_id'], $param['station_id'], date("Y-m-d", time()) . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                    $sql_forecast2     = 'select o3_8hour,station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $forecastList_o38h = Db::query($sql_forecast2, array($param['region_id'], $param['station_id'], date("Y-m-d", time()) . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                    //判断O3和O3_8h是否同时有数据，同时有数据选择O3_8h,否则哪个有数据取哪个
                    if (!empty($forecastList_o3) && !empty($forecastList_o38h)) {
                        $forecastList1 = $forecastList_o38h;
                    } else if (!empty($forecastList_o3) && empty($forecastList_o38h)) {
                        $forecastList1 = $forecastList_o3;
                    } else if (empty($forecastList_o3) && !empty($forecastList_o38h)) {
                        $forecastList1 = $forecastList_o38h;
                    }
                } else {
                    $sql_week1 = 'select ' . $param['contaminant_name1'] . ',publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                    $weekList1 = Db::query($sql_week1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', date("Y-m-d", strtotime("-1 day")) . ' 23:00:00'));
                    $sql_week2 = 'select ' . $param['contaminant_name2'] . ',publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                    $weekList2 = Db::query($sql_week2, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', date("Y-m-d", strtotime("-1 day")) . ' 23:00:00'));
                    //预报
                    $sql_forecast1 = 'select ' . $param['contaminant_name1'] . ',station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $forecastList1 = Db::query($sql_forecast1, array($param['region_id'], $param['station_id'], date("Y-m-d", time()) . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                    $sql_forecast2 = 'select ' . $param['contaminant_name2'] . ',station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $forecastList2 = Db::query($sql_forecast2, array($param['region_id'], $param['station_id'], date("Y-m-d", time()) . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                }
                if (empty($forecastList1)) {
                    $forecastList1 = [];
                }
                if (empty($forecastList2)) {
                    $forecastList2 = [];
                }
                $list1 = array_merge($weekList1, $forecastList1);
                $list2 = array_merge($weekList2, $forecastList2);
            } else {
                //预报（未来日期范围，包括今天）
                if ($param['contaminant_name1'] == 'O3') {
                    $sql1      = 'select O3,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $list_o3   = Db::query($sql1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                    $sql1      = 'select o3_8hour,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $list_o38h = Db::query($sql1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                    //判断O3和O3_8h是否同时有数据，同时有数据选择O3_8h,否则哪个有数据取哪个
                    if (!empty($list_o3) && !empty($list_o38h)) {
                        $list1 = $list_o38h;
                    } else if (!empty($list_o3) && empty($list_o38h)) {
                        $list1 = $list_o3;
                    } else if (empty($list_o3) && !empty($list_o38h)) {
                        $list1 = $list_o38h;
                    }
                    $sql2  = 'select ' . $param['contaminant_name2'] . ',predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $list2 = Db::query($sql2, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                } else if ($param['contaminant_name2'] == 'O3') {
                    $sql1  = 'select ' . $param['contaminant_name1'] . ',predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $list1 = Db::query($sql1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));


                    $sql2      = 'select O3,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $list_o3   = Db::query($sql2, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                    $sql2      = 'select o3_8hour,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $list_o38h = Db::query($sql2, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                    //判断O3和O3_8h是否同时有数据，同时有数据选择O3_8h,否则哪个有数据取哪个
                    if (!empty($list_o3) && !empty($list_o38h)) {
                        $list2 = $list_o38h;
                    } else if (!empty($list_o3) && empty($list_o38h)) {
                        $list2 = $list_o3;
                    } else if (empty($list_o3) && !empty($list_o38h)) {
                        $list2 = $list_o38h;
                    }

                } else {
                    $sql1  = 'select ' . $param['contaminant_name1'] . ',predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $list1 = Db::query($sql1, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                    $sql2  = 'select ' . $param['contaminant_name2'] . ',predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                    $list2 = Db::query($sql2, array($param['region_id'], $param['station_id'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                }
            }
        }
        $newList1 = [];
        $newList2 = [];
        if (count($list1) <= 0 && count($list2) <= 0) {
            $data['data'] = [];
            $this->success('暂无数据', $data);
        } else {
            foreach ($list1 as $k1 => $v1) {
                foreach ($list2 as $k2 => $v2) {
                    foreach ($v1 as $k3 => $v3) {
                        foreach ($v2 as $k4 => $v4) {
                            if ($k3 != 'pt_time' && $k4 != 'pt_time' && $k3 != 'station_id' && $k4 != 'station_id') {
                                if (strtolower($k3) == 'o3') {
                                    if (strtolower($k4) == 'o3') {
                                        if ($v1['pt_time'] == $v2['pt_time'] && $v1['o3'] > 0 && $v2['O3'] > 0) {
                                            $newList1[date("m/d", strtotime($v1['pt_time']))][] = $v1['o3'];
                                            $newList2[date("m/d", strtotime($v2['pt_time']))][] = $v2['O3'];
                                        }
                                    } else if (strtolower($k4) == 'o3_8hour') {
                                        if ($v1['pt_time'] == $v2['pt_time'] && $v1['o3'] > 0 && $v2['o3_8hour'] > 0) {
                                            $newList1[date("m/d", strtotime($v1['pt_time']))][] = $v1['o3'];
                                            $newList2[date("m/d", strtotime($v2['pt_time']))][] = $v2['o3_8hour'];
                                        }
                                    } else {
                                        if ($v1['pt_time'] == $v2['pt_time'] && $v1['o3'] > 0 && $v2[$param['contaminant_name2']] > 0) {
                                            $newList1[date("m/d", strtotime($v1['pt_time']))][] = $v1['o3'];
                                            $newList2[date("m/d", strtotime($v2['pt_time']))][] = $v2[$param['contaminant_name2']];
                                        }
                                    }

                                } else if (strtolower($k3) == 'o3_8hour') {
                                    if (strtolower($k4) == 'o3') {
                                        if ($v1['pt_time'] == $v2['pt_time'] && $v1['o3_8hour'] > 0 && $v2['O3'] > 0) {
                                            $newList1[date("m/d", strtotime($v1['pt_time']))][] = $v1['o3_8hour'];
                                            $newList2[date("m/d", strtotime($v2['pt_time']))][] = $v2['O3'];
                                        }
                                    } else if (strtolower($k4) == 'o3_8hour') {
                                        if ($v1['pt_time'] == $v2['pt_time'] && $v1['o3_8hour'] > 0 && $v2['o3_8hour'] > 0) {
                                            $newList1[date("m/d", strtotime($v1['pt_time']))][] = $v1['o3_8hour'];
                                            $newList2[date("m/d", strtotime($v2['pt_time']))][] = $v2['o3_8hour'];
                                        }
                                    } else {
                                        if ($v1['pt_time'] == $v2['pt_time'] && $v1['o3_8hour'] > 0 && $v2[$param['contaminant_name2']] > 0) {
                                            $newList1[date("m/d", strtotime($v1['pt_time']))][] = $v1['o3_8hour'];
                                            $newList2[date("m/d", strtotime($v2['pt_time']))][] = $v2[$param['contaminant_name2']];
                                        }
                                    }

                                } else {
                                    if (strtolower($k4) == 'o3') {
                                        if ($v1['pt_time'] == $v2['pt_time'] && $v1[$param['contaminant_name1']] > 0 && $v2['O3'] > 0) {
                                            $newList1[date("m/d", strtotime($v1['pt_time']))][] = $v1[$param['contaminant_name1']];
                                            $newList2[date("m/d", strtotime($v2['pt_time']))][] = $v2['O3'];
                                        }
                                    } else if (strtolower($k4) == 'o3_8hour') {
                                        if ($v1['pt_time'] == $v2['pt_time'] && $v1[$param['contaminant_name1']] > 0 && $v2['o3_8hour'] > 0) {
                                            $newList1[date("m/d", strtotime($v1['pt_time']))][] = $v1[$param['contaminant_name1']];
                                            $newList2[date("m/d", strtotime($v2['pt_time']))][] = $v2['o3_8hour'];
                                        }
                                    } else {
                                        if ($v1['pt_time'] == $v2['pt_time'] && $v1[$param['contaminant_name1']] > 0 && $v2[$param['contaminant_name2']] > 0) {
                                            $newList1[date("m/d", strtotime($v1['pt_time']))][] = $v1[$param['contaminant_name1']];
                                            $newList2[date("m/d", strtotime($v2['pt_time']))][] = $v2[$param['contaminant_name2']];
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        foreach ($lastYearWeek as $k => $v) {
            //计算相关指数

            if (isset($newList1[$v]) && isset($newList2[$v])) {
                if (count($newList1[$v]) >= 20 && count($newList2[$v]) >= 20) {
                    $data['data'][0][$k] = round(correlationAnalysis($newList1[$v], $newList2[$v]), 2);
                } else {
                    $data['data'][0][$k] = '';
                }

            } else {
                $data['data'][0][$k] = '';
            }
        }
        $this->success('成功', $data);
    }

    /**
     * 相关指数（站点）
     * zhugeng 2019-04-11
     */
    public function relevantStation()
    {
        $param = $this->request->param();
        if (empty($param['start_date']) || empty($param['end_date']) || empty($param['region_id']) || empty($param['contaminant_name'])) {
            $this->error('参数错误');
        }
        //获取所有站点
        $station_sql = Db::query('select name from basic_station');
        $stations    = [];
        foreach ($station_sql as $k => $v) {
            array_push($stations, $v['name']);
        }
        $param['contaminant_name'] = strtoupper($param['contaminant_name']);
        $param['contaminant_name'] = 'PM2.5' ? str_replace('.', '', $param['contaminant_name']) : $param['contaminant_name'];
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        $data['date'] = $lastYearWeek;
        if (empty($param['station_id1']) || empty($param['station_id2'])) {
            $data['data'] = [];
            $this->success('暂无数据', $data);
        }
        //判断预报值还是实际值
        if (strtotime($param['end_date']) < strtotime(date('Y-m-d', time()))) {
            //实际值(上周或者过去时间段)
            $sql_history1 = 'select ' . $param['contaminant_name'] . ',station_id,publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
            $list1        = Db::query($sql_history1, array($param['region_id'], $param['station_id1'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00'));
            $sql_history2 = 'select ' . $param['contaminant_name'] . ',station_id,publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
            $list2        = Db::query($sql_history2, array($param['region_id'], $param['station_id2'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00'));
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d', time())) + 1;
            if ($days > 1) {
                //实际+预报（本周或者今天日期在所选日期范围内）
                //实际
                $sql_week1 = 'select ' . $param['contaminant_name'] . ',station_id,publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                $weekList1 = Db::query($sql_week1, array($param['region_id'], $param['station_id1'], $param['start_date'] . ' 00:00:00', date("Y-m-d", strtotime("-1 day")) . ' 23:00:00'));
                $sql_week2 = 'select ' . $param['contaminant_name'] . ',station_id,publish_time as pt_time from air_quality_station_aqi_realtime_hour where region_id = ? and station_id = ? and publish_time between ? and ?';
                $weekList2 = Db::query($sql_week2, array($param['region_id'], $param['station_id2'], $param['start_date'] . ' 00:00:00', date("Y-m-d", strtotime("-1 day")) . ' 23:00:00'));
                //预报
                $sql_forecast1 = 'select ' . $param['contaminant_name'] . ',station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                $forecastList1 = Db::query($sql_forecast1, array($param['region_id'], $param['station_id1'], date("Y-m-d", time()) . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                $sql_forecast2 = 'select ' . $param['contaminant_name'] . ',station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                $forecastList2 = Db::query($sql_forecast2, array($param['region_id'], $param['station_id2'], date("Y-m-d", time()) . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                $list1         = array_merge($weekList1, $forecastList1);
                $list2         = array_merge($weekList2, $forecastList2);
            } else {
                //预报（未来日期范围，包括今天）
                $sql1  = 'select ' . $param['contaminant_name'] . ',station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                $list1 = Db::query($sql1, array($param['region_id'], $param['station_id1'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
                $sql2  = 'select ' . $param['contaminant_name'] . ',station_id,predict_time as pt_time from air_quality_station_aqi_forecast_hour where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
                $list2 = Db::query($sql2, array($param['region_id'], $param['station_id2'], $param['start_date'] . ' 00:00:00', $param['end_date'] . ' 23:00:00', date("Y-m-d", time())));
            }
        }
        $newList1 = [];
        $newList2 = [];
        if (count($list1) <= 0 && count($list2) <= 0) {
            $data['data'] = [];
            $this->success('暂无数据', $data);
        } else {

            foreach ($list1 as $k1 => $v1) {
                foreach ($list2 as $k2 => $v2) {
                    if ($v1['pt_time'] == $v2['pt_time'] && $v1[$param['contaminant_name']] > 0 && $v2[$param['contaminant_name']] > 0) {
                        $newList1[date("m/d", strtotime($v1['pt_time']))][] = $v1[$param['contaminant_name']];
                        $newList2[date("m/d", strtotime($v2['pt_time']))][] = $v2[$param['contaminant_name']];
                    }
                }
            }
        }
        foreach ($lastYearWeek as $k => $v) {
            //计算相关指数
            if (isset($newList1[$v]) && isset($newList2[$v])) {
                if (count($newList1[$v]) >= 20 && count($newList2[$v]) >= 20) {
                    $data['data'][0][$k] = round(correlationAnalysis($newList1[$v], $newList2[$v]), 2);
                } else {
                    $data['data'][0][$k] = '';
                }
            } else {
                $data['data'][0][$k] = '';
            }
        }

        $this->success('成功', $data);
    }

    /**
     * 相关站点（同一天一个或多个相关站点）
     * zhugeng 2019-04-12
     */
    public function relevantAllStation()
    {
        $param = $this->request->param();
        if (empty($param['start_date']) || empty($param['end_date']) || empty($param['region_id']) || empty($param['relevance_name'])) {
            $this->error('参数错误');
        }
        $param['relevance_name'] = strtolower($param['relevance_name']);
        $param['relevance_name'] = 'pm2.5' ? str_replace('.', '', $param['relevance_name']) : $param['relevance_name'];
        //获取所有站点
        $station_sql = Db::query('select station_id,name from basic_station');
        $stations    = [];
        foreach ($station_sql as $k => $v) {
            $stations[] = ['name' => $v['name'], 'station_id' => $v['station_id']];
        }
        unset($stations[0]);
//         $stations = array_values($stations);//去重，重新排列索引
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        $data['date'] = $lastYearWeek;
        //判断预报值还是实际值
        if (strtotime($param['end_date']) < strtotime(date('Y-m-d', time()))) {
            //实际值
            $sql_real = 'select ' . $param['relevance_name'] . ',station_id,publish_time as dt_time from air_quality_station_aqi_realtime_hour where region_id = ?  and publish_time between ? and ? and station_id != 0';
            $list     = Db::query($sql_real, array($param['region_id'], $param['start_date'], $param['end_date'] . ' 23:00:00'));
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d', time())) + 1;
            if ($days > 1) {
                //实际+预报
                //实际
                $sql_real  = 'select ' . $param['relevance_name'] . ',station_id,publish_time as dt_time from air_quality_station_aqi_realtime_hour where region_id = ?  and publish_time between ? and ? and station_id != 0';
                $list_real = Db::query($sql_real, array($param['region_id'], $param['start_date'], date("Y-m-d", strtotime("-1 day")) . ' 23:00:00'));
                //预报
                $sql_for  = 'select ' . $param['relevance_name'] . ',station_id,predict_time as dt_time from air_quality_station_aqi_forecast_hour where region_id = ?  and predict_time between ? and ? and publish_time = ? and station_id != 0';
                $list_for = Db::query($sql_for, array($param['region_id'], date("Y-m-d", time()), $param['end_date'] . ' 23:00:00', date("Y-m-d", time()) . ' 00:00:00'));
                $list     = array_merge_recursive($list_real, $list_for);
            } else {
                //预报
                $sql_real = 'select ' . $param['relevance_name'] . ',station_id,predict_time as dt_time from air_quality_station_aqi_forecast_hour where region_id = ?  and predict_time between ? and ? and publish_time = ? and station_id != 0';
                $list     = Db::query($sql_real, array($param['region_id'], $param['start_date'], $param['end_date'] . ' 23:00:00', date("Y-m-d", time()) . ' 00:00:00'));
            }
        }
        $newList  = [];
        $newDate  = [];
        $newDate1 = [];
        if (count($list) <= 0) {
            foreach ($lastYearWeek as $k => $v) {
                $data['data'][0][] = '';
            }
        } else {
            foreach ($list as $k2 => $v2) {
                if ($v2['station_id'] < 6) {
                    $newList[date('Y-m-d', strtotime($v2['dt_time']))][] = [$stations[$v2['station_id']]['name'] => $v2[$param['relevance_name']], 'station_id' => $v2['station_id'], 'dt_time' => $v2['dt_time']];
                    array_push($newDate, date('m/d', strtotime($v2['dt_time'])));
                    array_push($newDate1, date('Y-m-d', strtotime($v2['dt_time'])));
                    $newDate  = array_values(array_unique($newDate));//处理重复数据
                    $newDate1 = array_values(array_unique($newDate1));//处理重复数据
                }

            }
            $newList1 = [];
            foreach ($newList as $k => $v) {
                foreach ($v as $k1 => $v1) {
                    if ($v1['station_id'] == 1 && $v1[$stations[$v1['station_id']]['name']] > 0) {

                        $newList1[$k][1][] = ['value' => $v1[$stations[$v1['station_id']]['name']], 'dt_time' => $v1['dt_time']];
//                        $newList1[$k][1]['station_id'] = 1;
                    } else if ($v1['station_id'] == 2 && $v1[$stations[$v1['station_id']]['name']] > 0) {
                        $newList1[$k][2][] = ['value' => $v1[$stations[$v1['station_id']]['name']], 'dt_time' => $v1['dt_time']];
//                        $newList1[$k][2]['station_id'] = 2;
                    } else if ($v1['station_id'] == 3 && $v1[$stations[$v1['station_id']]['name']] > 0) {
                        $newList1[$k][3][] = ['value' => $v1[$stations[$v1['station_id']]['name']], 'dt_time' => $v1['dt_time']];
//                        $newList1[$k][3]['station_id'] = 3;
                    } else if ($v1['station_id'] == 4 && $v1[$stations[$v1['station_id']]['name']] > 0) {
                        $newList1[$k][4][] = ['value' => $v1[$stations[$v1['station_id']]['name']], 'dt_time' => $v1['dt_time']];
//                        $newList1[$k][4]['station_id'] = 4;
                    } else if ($v1['station_id'] == 5 && $v1[$stations[$v1['station_id']]['name']] > 0) {
                        $newList1[$k][5][] = ['value' => $v1[$stations[$v1['station_id']]['name']], 'dt_time' => $v1['dt_time']];
//                        $newList1[$k][5]['station_id'] = 5;
                    }
                }
            }
            $result = [];
            foreach ($newList1 as $k => $v) {
                for ($i = 1; $i < count($v); $i++) {

                    for ($b = $i + 1; $b <= count($v); $b++) {
                        $str1 = [];
                        $str2 = [];
                        for ($j = 0; $j < count($v[$i]); $j++) {
                            for ($a = 0; $a < count($v[$b]); $a++) {
                                if (isset($v[$i][$j]) && isset($v[$b][$a]) && $v[$i][$j]['dt_time'] == $v[$b][$a]['dt_time']) {
                                    $str1[] = $v[$i][$j]['value'];
                                    $str2[] = $v[$b][$a]['value'];
                                }
                            }
                        }
                        if (count($str1) >= 20 && count($str2) >= 20) {
                            $value = correlationAnalysis($str1, $str2);
                            if ($value >= 0.75) {
                                $result[$k][] = $i;
                                $result[$k][] = $b;
                            }
                        }
                        if (isset($result[$k])) {
                            $result[$k] = array_values(array_unique($result[$k]));//去重，重新排列索引
                        }
                    }

                }
            }

            $result1 = [];
            foreach ($result as $k => $v) {
                if (strtotime($k) < strtotime(date('Y-m-d', time()))) {//查站点实际表
                    foreach ($v as $k1 => $v1) {
                        if (strtoupper($param['relevance_name']) == 'O3') {
                            $sql     = 'select o3,o3_iaqi,o3_8hour,o3_8hour_iaqi from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time = ?';
                        } else {
                            $sql     = 'select ' . $param['relevance_name'] . ' from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time = ?';
                        }
                        $sqlList = Db::query($sql, array($param['region_id'], $v1, $k));
                        if (empty($sqlList)) {
                            $result1[date('m/d', strtotime($k))][] = ['name' => '', 'value' => ''];
                        } else {
                            if (strtoupper($param['relevance_name']) == 'O3') {
                                if ($sqlList[0]['o3_iaqi'] >= $sqlList[0]['o3_8hour_iaqi']) {
                                    $result1[date('m/d', strtotime($k))][] = ['name' => $stations[$v1]['name'], 'value' => $sqlList[0]['o3']];
                                } else {
                                    $result1[date('m/d', strtotime($k))][] = ['name' => $stations[$v1]['name'], 'value' => $sqlList[0]['o3_8hour']];
                                }
                            } else {
                                $result1[date('m/d', strtotime($k))][] = ['name' => $stations[$v1]['name'], 'value' => $sqlList[0][$param['relevance_name']]];
                            }

                        }

                    }
                } else {//查站点预报表
                    foreach ($v as $k1 => $v1) {
                        if (strtoupper($param['relevance_name']) == 'O3') {
                            $sql     = 'select o3,o3_iaqi,o3_8hour,o3_8h_iaqi from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time = ? and publish_time = ?';
                        } else {
                            $sql     = 'select ' . $param['relevance_name'] . ' from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time = ? and publish_time = ?';
                        }
                        $sqlList = Db::query($sql, array($param['region_id'], $v1, $k, date('Y-m-d', time())));
                        if (empty($sqlList)) {
                            $result1[date('m/d', strtotime($k))][] = ['name' => '', 'value' => ''];
                        } else {
                            if (strtoupper($param['relevance_name']) == 'O3') {
                                if ($sqlList[0]['o3_iaqi'] >= $sqlList[0]['o3_8h_iaqi']) {
                                    $result1[date('m/d', strtotime($k))][] = ['name' => $stations[$v1]['name'], 'value' => $sqlList[0]['o3']];
                                } else {
                                    $result1[date('m/d', strtotime($k))][] = ['name' => $stations[$v1]['name'], 'value' => $sqlList[0]['o3_8hour']];
                                }
                            } else {
                                $result1[date('m/d', strtotime($k))][] = ['name' => $stations[$v1]['name'], 'value' => $sqlList[0][$param['relevance_name']]];
                            }
                        }

                    }
                }
            }

            if (!empty($result1)) {
                $temp = [];
                foreach ($result1 as $k => $v) {
                    $temp[$k] = count($v);
                }
                for ($j = 0; $j < max($temp); $j++) {
                    foreach ($lastYearWeek as $k => $v) {
                        if (in_array($v, $newDate)) {
                            if (isset($result1[$v][$j])) {
                                if ($result1[$v][$j]['name'] == 'CO') {
                                    $result1[$v][$j]['value'] = round($result1[$v][$j]['value'], 1);
                                } else {
                                    $result1[$v][$j]['value'] = round($result1[$v][$j]['value']);
                                }
                                $data['data'][$j][] = $result1[$v][$j];
                            } else {
                                $data['data'][$j][] = ['name' => '', 'value' => ''];
                            }
                        } else {
                            $data['data'][$j][] = ['name' => '', 'value' => ''];
                        }
                    }
                }
            } else {
                $data['data'][0] = [];
            }
        }

        $this->success('成功', $data);
    }

    

    /**
     * 相关性分析-减排前贡献度（查询MongoDB）
     * zhugeng 2019-04-13
     */
    public function relevanceContributionStation()
    {
        //链接MongoDB数据库（远程）
        $PDOManager                 = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $opt                        = [
            'projection' => [],
        ];
        $param                      = $this->request->param();
        $param['contribution_name'] = strtoupper($param['contribution_name']);
        $param['contribution_name'] = 'PM2.5' ? str_replace('_', '', $param['contribution_name']) : $param['contribution_name'];
        if (empty($param['region_id']) || empty($param['industry_id']) || empty($param['start_date']) || empty($param['end_date'])) {
            $this->error('参数错误');
        }
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        $data['date'] = $lastYearWeek;
        //返回年月日
        $yearWeek     = self::getDateFromRangeYear($param['start_date'], $param['end_date']);
        $data['time'] = $yearWeek;

        // 1工业、2非工业
        if ($param['industry_id'] == 1) {
            //条件参数
            $map          = [
                "region_id"         => (int)$param['region_id'],
                "contribution_name" => $param['contribution_name'],//污染物
            ];
            $pollutantTab = 'huanxin.air_quality_pollutant_company_forecast_day';
        } else {
            //条件参数
            $map          = [
                // "region_id"         => (int)$param['region_id'],
                "contribution_name" => $param['contribution_name'],//污染物
            ];
            $pollutantTab = 'huanxin.air_quality_pollutant_non_industry_area_forecast_day';
        }
        //通过日期判断是预测值还是实际值
        if (strtotime($param['end_date']) < strtotime(date('Y-m-d'))) {
            //实际值(上周或者过去时间段)
            $map['predict_time'] = [
                '$gte' => date('Y-m-d 00:00:00', strtotime($param['start_date'])),
                '$lte' => date('Y-m-d 00:00:00', strtotime($param['end_date']))
            ];
            $map['$where']       = 'this.publish_time == this.predict_time';
            //预报值
            $query  = new \MongoDB\Driver\Query($map, $opt);//查询
            $cursor = $PDOManager->executeQuery($pollutantTab, $query)->toArray();
            $list   = json_decode(json_encode($cursor), true);
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d', time())) + 1;
            if ($days > 1) {
                //实际+预报（本周或者今天日期在所选日期范围内）
                //实际
                $map['$where'] = 'this.publish_time == this.predict_time';
                //预报
                $map['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00', strtotime($param['start_date'])),
                    '$lte' => date('Y-m-d 23:00:00', strtotime('-1 day'))
                ];
                //预报值
                $query  = new \MongoDB\Driver\Query($map, $opt);//查询
                $cursor = $PDOManager->executeQuery($pollutantTab, $query)->toArray();
                $list1  = json_decode(json_encode($cursor), true);

                //预报（未来日期范围，包括今天）
                unset($map['$where']);
                $map['publish_time'] = date('Y-m-d ' . (date('H:i') < '14:20' ? '00' : '14') . ':00:00');
                $map['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00'),
                    '$lte' => date('Y-m-d 23:00:00', strtotime($param['end_date']))
                ];
                //预报值
                $query  = new \MongoDB\Driver\Query($map, $opt);//查询
                $cursor = $PDOManager->executeQuery($pollutantTab, $query)->toArray();
                $list2  = json_decode(json_encode($cursor), true);
                $list   = array_merge_recursive($list1, $list2);
            } else {
                $map['predict_time'] = [
                    '$gte' => date('Y-m-d 00:00:00'),
                    '$lte' => date('Y-m-d 23:00:00', strtotime($param['end_date']))
                ];
                $map['publish_time'] = date('Y-m-d ' . (date('H:i') < '14:20' ? '00' : '14') . ':00:00');
//                $map['publish_time'] = date('Y-m-d', time()) . ' 14:00:00';
                //预报值
                $query  = new \MongoDB\Driver\Query($map, $opt);//查询
                $cursor = $PDOManager->executeQuery($pollutantTab, $query)->toArray();
                $list   = json_decode(json_encode($cursor), true);
            }

        }

        if (count($list) <= 0) {
            foreach ($lastYearWeek as $k => $v) {
                $data['data'][0][] = '';
                $data['data'][1][] = '';
                $data['data'][2][] = '';
                $data['data'][3][] = '';
                $data['data'][4][] = '';
            }
        } else {
            $newList = [];
            $newDate = [];
            for ($i = 0; $i < count($list); $i++) {
                $newList[date("m/d", strtotime($list[$i]['predict_time']))][] = $list[$i];
                array_push($newDate, date('m/d', strtotime($list[$i]['predict_time'])));
            }
            $newDate = array_values(array_unique($newDate));//去重，重新排列索引
            $service = new CommonService();
            foreach ($lastYearWeek as $k2 => $v2) {
                $changzhi = $deshengyuan = $jiance = $qinghua = $shenji = 0;
                if (in_array($v2, $newDate)) {
                    foreach ($newList[$v2] as $k => $v) {
                        if ($v['station_id'] == 1) {
                            $changzhi       += $v['contribution_degree'];
                            $concentration1 = $v['concentration'];
                        } else if ($v['station_id'] == 2) {
                            $deshengyuan    += $v['contribution_degree'];
                            $concentration2 = $v['concentration'];
                        } else if ($v['station_id'] == 3) {
                            $jiance         += $v['contribution_degree'];
                            $concentration3 = $v['concentration'];
                        } else if ($v['station_id'] == 4) {
                            $qinghua        += $v['contribution_degree'];
                            $concentration4 = $v['concentration'];
                        } else if ($v['station_id'] == 5) {
                            $shenji         += $v['contribution_degree'];
                            $concentration5 = $v['concentration'];
                        }
                    }
                    $data['data'][0][] = $service->contributionRound($changzhi / $concentration1);
                    $data['data'][1][] = $service->contributionRound($deshengyuan / $concentration2);
                    $data['data'][2][] = $service->contributionRound($jiance / $concentration3);
                    $data['data'][3][] = $service->contributionRound($qinghua / $concentration4);
                    $data['data'][4][] = $service->contributionRound($shenji / $concentration5);
                } else {
                    $data['data'][0][] = '';
                    $data['data'][1][] = '';
                    $data['data'][2][] = '';
                    $data['data'][3][] = '';
                    $data['data'][4][] = '';
                }
            }
        }
        $this->success('成功', $data);
    }

    /**
     * 相关性分析-贡献度明细（站点）
     * zhugeng 2019-04-13
     */
    public function relevanceContributionStationInfo()
    {
        //链接MongoDB数据库（远程）
        $PDOManager = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $param      = $this->request->param();
        if (empty($param['predict_time']) || empty($param['region_id'])) {
            $this->error('参数错误');
        }
        $industryType               = $param['industry_id'];
        $param['contribution_name'] = strtoupper($param['contribution_name']);
        $commonService              = new CommonService();
        if ($industryType == 1) {
            $pollutantTab = 'huanxin.air_quality_pollutant_company_forecast_day';
        } else {
            $pollutantTab = 'huanxin.air_quality_pollutant_non_industry_area_forecast_day';
        }
        //条件参数
        $map = [
            // "region_id"         => (int)$param['region_id'],
            "station_id"        => (int)$param['station_id'],
            "contribution_name" => $param['contribution_name'],
            "predict_time"      => date('Y-m-d 00:00:00', strtotime($param['predict_time'])),
        ];

        $options = [
            "_id"  => 0,
            'sort' => ['contribution_value' => -1, 'company_id' => 1],
        ];
        if (strtotime($param['predict_time']) < strtotime(date('Y-m-d'))) {
            $map['$where'] = 'this.publish_time == this.predict_time';
        } else {
            //预报
            $map['publish_time'] = date('Y-m-d ' . (date('H:i') < '14:20' ? '00' : '14') . ':00:00');
        }
        //预报值
        $query  = new \MongoDB\Driver\Query($map, $options);//查询
        $cursor = $PDOManager->executeQuery($pollutantTab, $query)->toArray();
        $list   = json_decode(json_encode($cursor), true);
        $data   = [];

        $data['data'] = [[]];
        $data['info'] = [];
        $data['date'] = [];
        //工业类型
        if ($industryType == 1) {
            $companyList = Db::query('select id,short_name from basic_company where id <= 60');
            if (!empty($list)) {
                foreach ($list as $k => $v) {
                    foreach ($companyList as $k1 => $v1) {
                        if ($v['company_id'] == $v1['id']) {
                            $data['date'][] = $v1['short_name'];
                        }
                    }
                    $data['data'][0][] = $commonService->contributionRound($v['contribution_value']);
                }
            }
        } else {//非工业类型
            $nonIndustryList = Db::query('select id,name from basic_industry where id in ' . Config::get('no_industry_limit_arr'));
            $non             = [];
            if (!empty($list)) {
                foreach ($list as $lv) {
                    $non[$lv['industry_id']][$lv['non_industry_region_id']] = $non[$lv['industry_id']][$lv['non_industry_region_id']] ?? 0;
                    $non[$lv['industry_id']][$lv['non_industry_region_id']] += $lv['contribution_value'];
                }
            }
            $industry_area = Db::query('select id,name from basic_non_industry_area');
            foreach ($nonIndustryList as $k => $v) {
                $data['date'][] = $v['name'];
                if (!empty($list)) {
                    //行业列表
                    $info = '';
                    $index = 0;
                    foreach ($industry_area as $v2) {
                        $exp = '  ';
                        if ($index % 4 == 0) {
                            $exp = '<br/>';
                        }
                        $contribution = $commonService->contributionRound($non[$v['id']][$v2['id']]);
                        $info         .= "{$v2['name']} : {$contribution}% {$exp}";
                        $index++;
                    }
                    $curIndustryVal    = $commonService->contributionRound(array_sum($non[$v['id']]));
                    $data['info'][$k]  = "{$v['name']} : {$curIndustryVal}%<br/><br/>{$info}";
                    $data['data'][0][] = $commonService->contributionRound(array_sum($non[$v['id']]));
                }
            }
        }
        $this->success('成功', $data);
    }

    /**
     * 相关污染物
     * zhugeng 2019-04-10
     */
    public function relevantContaminant()
    {
        $param = $this->request->param();
        if (empty($param['start_date']) || empty($param['end_date']) || empty($param['region_id'])) {
            $this->error('参数错误');
        }
        $data = [];
        //日期列表
        $lastYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        $data['date'] = $lastYearWeek;
        //通过日期判断是预测值还是实际值
        if (strtotime($param['end_date']) <= strtotime(date('Y-m-d', time()))) {
            //实际值(上周或者过去时间段)
            $sql_history = "select name,value,publish_time as pt_time from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
            $list        = Db::query($sql_history, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
        } else {
            //计算今天到结束日期相差天数
            $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d', time())) + 1;
            if ($days > 1) {
                //实际+预报（本周或者今天日期在所选日期范围内）
                //实际
                $sql_week = "select name,value,publish_time as pt_time from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
                $weekList = Db::query($sql_week, array($param['region_id'], $param['station_id'], $param['start_date'], date("Y-m-d", strtotime("-1 day"))));
                //预报
                $sql_forecast = "select name,value,predict_time as pt_time from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                $forecastList = Db::query($sql_forecast, array($param['region_id'], $param['station_id'], date("Y-m-d", time()), $param['end_date'], date("Y-m-d", time())));
                if (count($weekList) > 0 && count($forecastList) > 0) {
                    $list = array_merge($weekList, $forecastList);
                } else {
                    if (count($weekList) > 0) {
                        $list = $weekList;
                    }
                    if (count($forecastList) > 0) {
                        $list = $forecastList;
                    }
                }
            } else {
                //预报（未来日期范围，包括今天）
                $sql  = "select name,value,predict_time as pt_time from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                $list = Db::query($sql, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date'], date("Y-m-d", time())));
            }
        }
        $num = '';
        if (count($list) <= 0) {
            foreach ($lastYearWeek as $k => $v) {
                $data['data'][0][] = ['name' => '', 'value' => '', 'type' => 1];
            }
        } else {
            $newList = [];
            $newDate = [];
            for ($i = 0; $i < count($list); $i++) {
                $newList[date("m/d", strtotime($list[$i]['pt_time']))][] = $list[$i];
                array_push($newDate, date('m/d', strtotime($list[$i]['pt_time'])));
            }
            $newDate = array_values(array_unique($newDate));//去重，重新排列索引
            foreach ($newList as $k1 => $v1) {
                //处理O3和O3_8H
                for ($i = 0; $i < count($v1); $i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList[$k1], $i, 1);//删除数组元素，索引重组
                        }
                    }
                }
            }
            $temp = [];
            foreach ($newList as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            $num = max($temp);
            foreach ($lastYearWeek as $k => $v) {
                for ($j = 0; $j < $num; $j++) {
                    if (isset($newList[$v][$j])) {
                        if (in_array($v, $newDate)) {
                            if (strtoupper($newList[$v][$j]['name']) == 'O3_8H') {
                                $newList[$v][$j]['name'] = 'O3';
                            }
                            if (strtoupper($newList[$v][$j]['name']) == 'CO') {
                                $newList[$v][$j]['value'] = round($newList[$v][$j]['value'], 1);
                            } else {
                                $newList[$v][$j]['value'] = round($newList[$v][$j]['value']);
                            }
                            $data['data'][$j][] = ['name' => strtoupper($newList[$v][$j]['name']), 'value' => $newList[$v][$j]['value'], 'type' => 1];
                        } else {
                            $data['data'][$j][] = ['name' => '', 'value' => '', 'type' => 1];
//                            if ($v == date('m/d',time())) {
//                                $sql = "select name,value,predict_time as pt_time from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time = ? and predict_time = publish_time";
//                                $todayList = Db::query($sql,array($param['region_id'],$param['station_id'],date('Y-m-d',time())));
//                                if (count($todayList) > 0) {
//                                    $data['data'][$j][] = ['name'=>$todayList[0]['name'],'value'=>$todayList[0]['value'],'type'=>1];
//                                } else {
//                                    $data['data'][$j][] = ['name'=>'','value'=>'','type'=>1];
//                                }
//                            } else {
//                                $data['data'][$j][] = ['name'=>'','value'=>'','type'=>1];
//                            }
                        }
                    } else {
                        $data['data'][$j][] = ['name' => '', 'value' => '', 'type' => 1];
                    }
                }

            }
        }
        if ($param['station_id'] != 0) {
            //通过日期判断是预测值还是实际值(相关污染物)
            if (strtotime($param['end_date']) < strtotime(date('Y-m-d', time()))) {
                //实际值(上周或者过去时间段)
                $sql_history1 = "select primary_name,primary_value,relevance_name,relevance_value,publish_time as dt_time from air_quality_station_relevance_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between  ? and ? and pearson_value >= 0.75";
                $pollutant1   = Db::query($sql_history1, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
            } else {
                //计算今天到结束日期相差天数
                $days = $this->diffBetweenTwoDays($param['start_date'], date('Y-m-d', time())) + 1;
                if ($days > 1) {
                    //实际+预报（本周或者今天日期在所选日期范围内）
                    //实际
                    $sql_week1 = "select primary_name,primary_value,relevance_name,relevance_value,publish_time as dt_time from air_quality_station_relevance_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between  ? and ? and pearson_value >= 0.75";
                    $weekList1 = Db::query($sql_week1, array($param['region_id'], $param['station_id'], $param['start_date'], date("Y-m-d", strtotime("-1 day"))));
                    //预报
                    $sql_forecast1 = "select primary_name,primary_value,relevance_name,relevance_value,predict_time as dt_time from air_quality_station_relevance_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ? and pearson_value >= 0.75";
                    $forecastList1 = Db::query($sql_forecast1, array($param['region_id'], $param['station_id'], date("Y-m-d", time()), $param['end_date'], date("Y-m-d", time()) . ' 00:00:00'));
                    $pollutant1    = array_merge_recursive($weekList1, $forecastList1);
                } else {
                    //预报（未来日期范围，包括今天）
                    $sql1       = "select primary_name,primary_value,relevance_name,relevance_value,predict_time as dt_time from air_quality_station_relevance_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ? and pearson_value >= 0.75";
                    $pollutant1 = Db::query($sql1, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date'], date("Y-m-d", time())));
                }
            }
            if (count($pollutant1) <= 0) {
                foreach ($lastYearWeek as $k => $v) {
                    $data['data'][1][] = ['name' => '', 'value' => '', 'type' => 2];
                }
            } else {
                $newList1         = [];
                $newDate1         = [];
                $newDatePollutant = [];
                for ($i = 0; $i < count($pollutant1); $i++) {
                    $newList1[date("Y-m-d", strtotime($pollutant1[$i]['dt_time']))][] = $pollutant1[$i];
                    array_push($newDate1, date('m/d', strtotime($pollutant1[$i]['dt_time'])));
                    array_push($newDatePollutant, date('Y-m-d', strtotime($pollutant1[$i]['dt_time'])));
                }
                foreach ($newList1 as $k => $v) {
                    $newList1[$k] = array_values(array_unique(array_column($v, 'relevance_name')));
                }
                foreach ($newList1 as $k1 => $v1) {
                    foreach ($newList as $k2 => $v2) {
                        foreach ($v2 as $k3 => $v3) {
                            foreach ($v1 as $k4 => $v4) {
                                if (date('m/d', strtotime($k1)) == $k2 && $v4 == $v3['name']) {
                                    array_splice($newList1[$k1], $k4, 1);//删除数组元素，索引重组
                                }
                            }

                        }

                    }
                    //处理O3和O3_8H
                    for ($i = 0; $i < count($v1); $i++) {
                        foreach ($v1 as $k2 => $v2) {
                            if (strtoupper($v2) == 'O3' && strtoupper($v1[$i]) == 'O3_8H') {
                                array_splice($newList1[$k1], $i, 1);//删除数组元素，索引重组
                            }
                        }
                    }
                }
                $temp = [];
                foreach ($newList1 as $k1 => $v1) {
                    $temp[$k1] = count($v1);
                }
                $stationList = [];
                foreach ($newList1 as $k2 => $v2) {
                    foreach ($v2 as $k3 => $v3) {
                        if ($v3 == 'PM2.5' || $v3 == 'PM2_5') {
                            $v3 = 'pm25';
                        }
                        if (strtotime(date('Y-m-d', strtotime($k2))) < strtotime(date('Y-m-d', time()))) {
                            if (strtolower($v3) == 'O3') {
                                $sqlAqi    = 'select O3 from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time = ?';
                                $listValue = Db::query($sqlAqi, array($param['region_id'], $param['station_id'], $k2));
                                if (empty($listValue)) {
                                    $sqlAqi = 'select O3_8H from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time = ?';
                                }
                            } else {
                                $sqlAqi = 'select ' . strtolower($v3) . ' from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time = ?';
                            }


                        } else {
                            if (strtolower($v3) == 'O3') {
                                $sqlAqi    = 'select O3 from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time = ? and publish_time = ?';
                                $listValue = Db::query($sqlAqi, array($param['region_id'], $param['station_id'], $k2, date('Y-m-d', time())));
                                if (empty($listValue)) {
                                    $sqlAqi = 'select O3_8H from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time = ? and publish_time = ?';
                                }
                            } else {
                                $sqlAqi = 'select ' . strtolower($v3) . ' from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time = ? and publish_time = ?';
                            }

                        }
                        $listValue = Db::query($sqlAqi, array($param['region_id'], $param['station_id'], $k2, date('Y-m-d', time())));
                        if (!empty($listValue)) {
                            $stationList[date('m/d', strtotime($k2))][$k3][] = ['name' => $v3, 'value' => $listValue[0][strtolower($v3)]];
                        }

                    }
                }
                foreach ($lastYearWeek as $k => $v) {
                    for ($j = 0; $j < max($temp); $j++) {
                        if (isset($stationList[$v][$j])) {
                            if (in_array($v, $newDate1)) {
                                if (count($data['data'][0]) <= 0) {
                                    foreach ($lastYearWeek as $k => $v) {
                                        $data['data'][$j + $num][] = ['name' => '', 'value' => '', 'type' => 2];
                                    }
                                } else {
                                    if (!empty($stationList[$v][$j][0])) {
                                        if (strtoupper($stationList[$v][$j][0]['name']) == 'PM25') {
                                            $stationList[$v][$j][0]['name'] = 'PM2.5';
                                        }
                                        if (strtoupper($stationList[$v][$j][0]['name']) == 'CO') {
                                            $stationList[$v][$j][0]['value'] = round($stationList[$v][$j][0]['value'], 1);
                                        } else {
                                            $stationList[$v][$j][0]['value'] = round($stationList[$v][$j][0]['value']);
                                        }
                                        $data['data'][$j + $num][] = ['name' => strtoupper($stationList[$v][$j][0]['name']), 'value' => $stationList[$v][$j][0]['value'], 'type' => 2];
                                    } else {
                                        $data['data'][$j + $num][] = ['name' => '', 'value' => '', 'type' => 2];
                                    }
                                }

                            } else {
                                $data['data'][$j + $num][] = ['name' => '', 'value' => '', 'type' => 2];
//                                if ($v == date('m/d',time())) {
//                                    $sql = 'select '.strtolower($newList1[date('m/d',strtotime($v))][$j]).' from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time = ?';
//                                    $todayList = Db::query($sql,array($param['region_id'],$param['station_id'],date('Y-m-d',time())));
//                                    if (count($todayList) > 0) {
//                                        $data['data'][$j+$num][] = ['name'=>$newList1[date('m/d',strtotime($v))][$j],'value'=>$todayList[0][$newList1[date('m/d',strtotime($v))][$j]],'type'=>2];
//                                    } else {
//                                        $data['data'][$j+$num][] = ['name'=>'','value'=>'','type'=>2];
//                                    }
//                                } else {
//                                    $data['data'][$j+$num][] = ['name'=>'','value'=>'','type'=>2];
//                                }
                            }
                        } else {
                            $data['data'][$j + $num][] = ['name' => '', 'value' => '', 'type' => 2];
                        }
                    }

                }
            }
        }
        $this->success('成功', $data);

    }

    /**
     * @param string $day1 开始日期
     * @param string $day2 结束日期
     * @return float|int 相差天数
     * @author zhugeng 2019-05-07
     */
    function diffBetweenTwoDays($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp     = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    /**
     * 获取指定日期段内每一天的日期(m/d)
     * @param string $startdate 开始日期
     * @param string $enddate 结束日期
     * @return array
     */
    function getDateFromRange($startdate, $enddate)
    {
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400 + 1;
        // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('m/d', $stimestamp + (86400 * $i));
        }
        return $date;
    }

    /**
     * 获取指定日期段内每一天的日期(Y-m-d)
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return array
     */
    function getDateFromRangeYear($startDate = '', $endDate = '')
    {
        $stimestamp = strtotime($startDate);
        $etimestamp = strtotime($endDate);
        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400 + 1;
        // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('Y-m-d', $stimestamp + (86400 * $i));
        }
        return $date;
    }

    /**
     * @param $companyId int 公司id
     * @param $region_id int 城市id
     * @param $industry_id int 工业、非工业
     * @return array|mixed
     * @author  zhugeng
     */
    public function companyInfo($companyId, $region_id, $industry_id)
    {
        if (empty($companyId) || empty($region_id) || empty($industry_id)) {
            $this->error('参数错误');
        }
        if ($industry_id == 1) {
            $industry = 'industry_id in' . Config::get('industry_limit_arr');
        } else {
            $industry = 'industry_id in' . '(8,9,10,11)';
        }
        $sql  = 'select short_name from basic_company where id = ? and region_id = ? and ' . $industry;
        $list = Db::query($sql, array($companyId, $region_id));
        if (count($list) <= 0) {
            return $list = array(0 => ['short_name' => '']);
        }
        return $list;
    }

    //科学计数法
    public function sctonum($num, $double = 5)
    {
        if (false !== stripos($num, "e")) {
            $a = explode("e", strtolower($num));
            return bcmul($a[0], bcpow(10, $a[1], $double), $double);
        }
        if (false !== stripos($num, "E")) {
            $a = explode("E", strtolower($num));
            return bcmul($a[0], bcpow(10, $a[1], $double), $double);
        }
        return $num;
    }

}